package com.mzw.project.common;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mzw.project.model.dto.user.UserLoginRequest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author L1nAn
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {
   private StringRedisTemplate stringRedisTemplate;

   public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
      this.stringRedisTemplate = stringRedisTemplate;
   }

   @Override
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      String token = request.getHeader("authorization");
      if (StrUtil.isBlank(token)) {
         return true;
      }
      String key =  "login:token:" + token;
      String jsonStr = stringRedisTemplate.opsForValue().get(key);
      if (jsonStr == null) {
         return true;
      }
      JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
      UserLoginRequest userDTO = JSONUtil.toBean(jsonObject, UserLoginRequest.class);
      UserHolder.saveUser(userDTO);
      stringRedisTemplate.expire(key, 30L,
              TimeUnit.MINUTES);
      return true;
   }

   @Override
   public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
      UserHolder.removeUser();
   }
}
